package com.yiqi.news.mvp.presenter

import android.app.Application

import com.jess.arms.integration.AppManager
import com.jess.arms.di.scope.ActivityScope
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.http.imageloader.ImageLoader
import com.yiqi.news.app.utils.RxUtils
import com.yiqi.news.entity.BaseResponse
import com.yiqi.news.entity.CashRecord
import com.yiqi.news.entity.Page
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import javax.inject.Inject

import com.yiqi.news.mvp.contract.RecordContract
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/18/2019 18:19
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
class RecordPresenter
@Inject
constructor(model: RecordContract.Model, rootView: RecordContract.View) :
        BasePresenter<RecordContract.Model, RecordContract.View>(model, rootView) {
    @Inject
    lateinit var mErrorHandler: RxErrorHandler
    @Inject
    lateinit var mApplication: Application
    @Inject
    lateinit var mImageLoader: ImageLoader
    @Inject
    lateinit var mAppManager: AppManager

    private var page = 1

    override fun onDestroy() {
        super.onDestroy();
    }

    fun requestCashRecord(isRefresh: Boolean) {
        if (isRefresh) page = 1
        mModel.cashRecord(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally { mRootView.complete(isRefresh) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseResponse<Page<CashRecord>>>(mErrorHandler) {
                    override fun onNext(t: BaseResponse<Page<CashRecord>>) {
                        if (t.isSuccess) {
                            mRootView.setData(t.data.list, isRefresh)
                            mRootView.hasMore(t.data.currPage < t.data.totalPage)
                            page++
                        }
                    }
                })
    }
}
